<template>
  <el-dialog
    :modelValue="showDlg"
    :title="title"
    width="500px"
    :before-close="handleClose"
  >
    <div>
      <el-form
        :model="formData"
        label-width="100px"
        ref="formRef"
        :rules="formRule"
        inline
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            clearable
            v-model="formData.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
       
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveForm(formRef)">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElButton } from 'element-plus'
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { reqAddROLE,reqUpdateROLE } from '@/api/acl/role/role'
import type { RoleData } from '@/api/acl/role/type'

let $emit = defineEmits('closeDlg', 'saveDlg')
import type { FormInstance, FormRules } from 'element-plus'
let props = defineProps({
  showDlg: {
    type: Boolean,
    default: false,
  },
  id: Number,
  roleName:String
})
let formData = reactive<RoleData>({
  roleName: '',
})
const formRef = ref<FormInstance>()
const formRule = reactive<FormRules>({
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
})
onMounted(() => {
  formData.roleName = props.roleName||''
})
const title = computed(() => {
  return props.id ? '修改' : '新增'
})

const handleClose = () => {
  $emit('closeDlg', false)
}
const saveForm = async (formRef: FormInstance | undefined) => {
  if (!formRef) return
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      const res = props.id? await reqAddROLE(formData): await reqUpdateROLE(formData)
      console.log(res)
      if (res.code == 200) {
        ElMessage.success(formData.id ? '修改成功' : '新增成功')
      } else {
        ElMessage.warning('新增失败')
      }
      $emit('saveDlg', false)
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>
<style lang="scss" scoped>
::v-deep .el-input,
.el-form-item {
  width: 100%;
}
</style>
